package thread_try;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyThread extends Thread {
    public void run(){
//        while(!interrupted()){
//
//        }
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"test"+i);
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("Thread run end");
    }

    public synchronized void func(){
        for (int i = 0; i < 10; i++) {
            if (i == 5) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName()+"func");
        }
    }

    public void funb(){
        synchronized (this){
            for (int i = 0; i < 10; i++) {
                if(i==3){
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println(Thread.currentThread().getName()+"funb");
            }
        }
    }

    public void funa(){
        synchronized (this){
            for (int i = 0; i < 20; i++) {
                System.out.println(Thread.currentThread().getName()+"funa");
            }
            notifyAll();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService1 = Executors.newCachedThreadPool();
        MyThread mt = new MyThread();
        executorService1.execute(mt::func);
        executorService1.execute(mt::funb);
        executorService1.execute(mt::funa);

        executorService1.shutdown();

//        MyThread m = new MyThread();
//        m.start();

        // 这里是将m当作runnable用了增加开销
//        Thread thread=new Thread(m);
//        thread.start();
        // 中断测试
//        thread.interrupt();

//        new Thread(()->{
//            for (int i = 0; i < 10; i++) {
//                System.out.println(Thread.currentThread().getName()+" :"+i);
//            }
//        },"蓝色").start();
//
//        new Thread(()->{
//            for (int i = 0; i < 10; i++) {
//                System.out.println(Thread.currentThread().getName()+" :"+i);
//                try {
//                    m.join();
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        },"绿色").start();
    }
}
